from annoying.decorators import render_to
from django.db.models import Count

from core.models import Event
from core.forms import SearchForm
from core.lib import SearchOrdering


@render_to('event/list.html')
def list(request):
    events = Event.objects.filter(status=Event.Status.Scheduled)
    if request.method == 'POST':        
        search_form = SearchForm(request.POST)
        if search_form.is_valid():
            if search_form.cleaned_data['city'] is not None and \
                search_form.cleaned_data['city'] != '0':
                events = events.filter(city=search_form.cleaned_data['city'])
            if search_form.cleaned_data['cost'] is not None:
                events = events.filter(current_sum_for_user__lte=search_form.cleaned_data['cost'])
            if search_form.cleaned_data['datetime'] is not None:
                events = events.filter(date__lte=search_form.cleaned_data['datetime'])
            events = {
                      str(SearchOrdering.by_name): events.order_by('name'),
                      str(SearchOrdering.by_cost): events.order_by('-cost'),
                      str(SearchOrdering.by_cost_per_user): events.order_by('-current_sum_for_user'),
                      str(SearchOrdering.by_participants): events.annotate(participants_count=Count('participants')).order_by('-participants_count'),
                      }.get(search_form.cleaned_data['ordering'], events)
    else:
        search_form = SearchForm()
    return {'events': events, 'search_form': search_form}
